#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import sys
import json
import bbki
import mrget
# import elemlib
sys.path.append('/usr/lib64/fpemud-os-sysman')
from fm_util import Util
from fm_util import InfoPrinter
from helper_bbki import BbkiWrapper
from helper_pkg_warehouse import PkgWarehouse
from helper_pkg_warehouse import CloudOverlayDb


p = InfoPrinter(indent=int(sys.argv[1]))
bSync = Util.str01ToBool(sys.argv[2])
bootEntrySpecStr = sys.argv[3]                  # this argument can be "" when (bSync == False)

mrget.init(system_or_user=True)

# sync BBKI information
if bSync:
    p.printInfo(">> Synchronizing BBKI information...")
    bootEntrySpec = bbki.BootEntrySpec(json.loads(bootEntrySpecStr))
    BbkiWrapper(None, bStrict=False).sync(bootEntrySpec)
    print("")

# update cloud overlay db
overlayDb = CloudOverlayDb()
if bSync or not overlayDb.isUpdateComplete():
    p.printInfo(">> Synchronizing cloud overlay database...")
    overlayDb.update()
    print("")

# sync repository directories
pkgwh = PkgWarehouse()
for repoName in pkgwh.repoman.getRepositoryList():
    if bSync or not pkgwh.repoman.isRepoExist(repoName):
        repoDir = pkgwh.repoman.getRepoDir(repoName)
        p.printInfo(">> Synchronizing repository \"%s\"..." % (repoName))
        pkgwh.repoman.syncRepository(repoName)
        print("")

# sync overlay directories
for overlayName in pkgwh.layman.getOverlayList():
    if pkgwh.layman.getOverlayType(overlayName) == "static":
        continue
    if bSync or not pkgwh.layman.isOverlayExist(overlayName):
        p.printInfo(">> Synchronizing overlay \"%s\"..." % (overlayName))
        pkgwh.layman.syncOverlay(overlayName)
        print("")

# add pre-enabled overlays
for oname, ourl in pkgwh.getPreEnableOverlays().items():
    if not pkgwh.layman.isOverlayExist(oname):
        p.printInfo(">> Installing overlay \"%s\"..." % (oname))
        vcsType = "git"
        if overlayDb.hasOverlay(oname):
            vcsType, ourl = overlayDb.getOverlayVcsTypeAndUrl(oname)
        else:
            if ourl is None:
                raise Exception("no URL for overlay %s" % (oname))
            if ourl.startswith("mirror://"):
                ourl = mrget.target_urls(ourl)[0]
        pkgwh.layman.addTrustedOverlay(oname, vcsType, ourl)
        print("")

# add pre-enabled overlays by pre-enabled package
for oname, data in pkgwh.getPreEnablePackages().items():
    ourl = data[0]
    if not pkgwh.layman.isOverlayExist(oname):
        p.printInfo(">> Installing overlay \"%s\"..." % (oname))
        vcsType = "git"
        if overlayDb.hasOverlay(oname):
            vcsType, ourl = overlayDb.getOverlayVcsTypeAndUrl(oname)
        else:
            if ourl is None:
                raise Exception("no URL for overlay %s" % (oname))
            if ourl.startswith("mirror://"):
                ourl = mrget.target_urls(ourl)[0]
        pkgwh.layman.addTransientOverlay(oname, vcsType, ourl)
        print("")

# add pre-enabled packages
for oname, data in pkgwh.getPreEnablePackages().items():
    tlist = [x for x in data[1] if not pkgwh.layman.isOverlayPackageEnabled(oname, x)]
    if len(tlist) > 0:
        p.printInfo(">> Enabling packages in overlay \"%s\"..." % (oname))
        for pkg in tlist:
            print("        - \"%s\"..." % (pkg))
            pkgwh.layman.enableOverlayPackage(oname, pkg, quiet=True)
        print("")

# refresh package related stuff
pkgwh.pythonRefreshTargetUseFlags()
pkgwh.rubyRefreshTargetUseFlags()

# eliminate "Performing Global Updates"
pkgwh.touchPortageTree()
